package org.teremail.service;

import java.util.ArrayList;
import java.util.List;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;

public class ServiceRegistrarImpl implements ServiceRegistrar {

    final List<Service> services = new ArrayList<Service>();
    private final MBeanServer mbeanServer;
    
    @Inject
    public ServiceRegistrarImpl(MBeanServer mbeanServer) {
        this.mbeanServer = mbeanServer;
    }

    public void register(Service service) {
        services.add(service);
    }
    
    public ServiceManagerMBean createServiceManager() {
        ServiceManager serviceManager = new ServiceManager(ImmutableList.copyOf(services));
        try {
            mbeanServer.registerMBean(serviceManager, new ObjectName("org.teremail", "name", "server"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return serviceManager;
    }

}
